<template>
  <div class="user-login">
    <div class="main-header">
      <!-- <a href class="main-header-logo">
        <img :src="logo" alt />
        <span>我爱报销</span>
      </a> -->
    </div>
    <div class="login-box">
      <div class="logo" v-show="showBottom">
        <img :src="logo" alt />
      </div>
      <van-tabs
        :border="false"
        v-model="active"
        color="#006CFF"
        line-width="50%"
        line-height="1"
        title-active-color="#006CFF"
        title-inactive-color="#979797"
      >
        <van-tab title="账号登录"></van-tab>
        <van-tab title="验证码登录"></van-tab>
      </van-tabs>
      <van-cell-group :border="false">
        <van-field
          @focus="onFocus"
          @blur="onBlur"
          v-model.trim="phone"
          placeholder="请输入手机号"
        >
          <template #label>
            +86
            <van-icon class="icon-arrow" name="arrow" />
          </template>
          <template v-if="active == 1" #right-icon>
            <span class="get-code-btn" @click="isBool&&getVCode()">{{
              VCodeText
            }}</span>
          </template>
        </van-field>
        <!-- 密码输入框 -->
        <van-password-input
          v-if="active == 1"
          class="password-input"
          :border="false"
          :value="code"
          :mask="false"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
        <van-field
          @keyup.enter="login()"
          type="password"
          v-if="active == 0"
          @focus="onFocus"
          @blur="onBlur"
          v-model="password"
          placeholder="请输入密码"
        />
      </van-cell-group>

      <div class="agreement" @click="isChecked = !isChecked">
        <template v-if="active == 0">
          <van-checkbox v-model="isRememberPwd" shape="square" icon-size="14"
            >记住密码</van-checkbox
          >
        </template>
        <template v-if="active == 1">
          <van-checkbox v-model="isChecked" shape="square" icon-size="14"
            >我已阅读且同意相关</van-checkbox
          >
          <router-link
            :to="{
              path: '/agreement',
              name: 'Agreement',
              params: { phone: phone, code: code }
            }"
            tag="span"
            style="font-weight: 700;"
            >《服务条款》和《隐私政策》</router-link
          >
        </template>
      </div>

      <!-- <div class="agreement1" @click="isChecked=!isChecked" v-if="this.active == 0"></div> -->
      <van-button
        @click="login()"
        style="width: 100%;"
        class="login-button"
        color="#006CFF"
        type="info"
        round
        >登录</van-button
      >
      <div class="recBottom">
        <div @click="forgetPwd">忘记密码</div>
        <div @click="callStaff">联系客服</div>
        <div @click="registered">立即注册</div>
        <!-- <div>如何加入推广人计划?</div> -->
      </div>
    </div>

    <center style="width: 100%;" v-show="showBottom">
      <div v-if="active == 0" class="policy">
        登录即代表您已同意<router-link
          :to="{
            path: '/agreement',
            name: 'Agreement',
            params: { phone: phone, code: code }
          }"
          class="policy_a"
          >《服务条款》和《隐私政策》</router-link
        >
      </div>
      <div>Copyright © 2019 IBX.All Rights Reserved.</div>
      <div></div>
      <div> <a href="https://beian.miit.gov.cn/">鄂ICP备2021002405号-2</a></div>
      <!-- <div>
        <img src alt />武汉溟宇科惠知识产权服务有限公司
      </div> -->
    </center>

    <!-- 数字键盘 -->
    <van-number-keyboard
      :show="showKeyboard"
      @input="onInput"
      @delete="onDelete"
      @blur="showKeyboard = false"
    ></van-number-keyboard>
  </div>
</template>

<script>
import { validation } from "@/utils/validate.js";
import { codeLogin, getCode, pwdLogin } from "@/api/login";
import { Dialog, Toast } from "vant";
import axios from "axios";
import config from "../../../public/config";
export default {
  data() {
    return {
      isBool:true,
      phone: "",
      password: "",
      code: "",
      active: 0,
      loginType: 0,
      isSelectUserType: true,
      isChecked: false,
      showKeyboard: false,
      VCodeText: "获取验证码",
      isAutoLogin: false,
      showBottom: true,
      logo: require("@/assets/img/login_logo.png"),
      isRememberPwd: false
    };
  },
  created() {
    localStorage.removeItem(config.get("v") + "_init");
    if (this.$route.query.phone) {
      this.phone = atob(this.$route.query.phone);
    }
    if (this.$route.params.phone) {
      this.phone = atob(this.$route.params.phone);
    }
    if (this.$route.params.active) {
      this.active = Number(this.$route.params.active);
    }
    if (this.$route.params.code) {
      this.code = this.$route.params.code;
    }
    let accountPassword = JSON.parse(localStorage.getItem("$accountPassword"));
    if (accountPassword && accountPassword.isRememberPwd) {
      this.phone = window.atob(accountPassword.phone);
      this.password = window.atob(accountPassword.password);
      this.isRememberPwd = accountPassword.isRememberPwd;
    }
    console.log(config.get("v"));
  },
  computed: {
    btoaPhone() {
      return btoa(this.phone);
    }
  },
  mounted() {
      // console.log('系统关闭')
      // let tip = "3月21日"
      // Dialog.alert({
      //   title: "提示",
      //   message: `${tip}起系统暂时关闭，开放时间待通知......`,
      // });
  },
  //缓存也会走的钩子
  deactivated() {
    this.$destroy(true); //销毁组件
  },
  methods: {
    registered() {
      this.$router.push("/register");
    },
    forgetPwd() {
      this.$router.push("/forgetPwd");
    },
    onInput(key) {
      this.code = (this.code + key).slice(0, 6);
    },
    onDelete() {
      this.code = this.code.slice(0, this.code.length - 1);
    },
    onFocus(data) {
      this.showBottom = false;
      data.path[3].style["border-color"] = "#006CFF";
    },
    onBlur(data) {
      this.showBottom = true;
      data.path[3].style["border-color"] = "#ebedf0";
    },
    callStaff(){
      Dialog.confirm({
        title: "提示",
        message: `点击确认将离开本页面跳转到手机拨号`
      })
        .then(() => {
          // on confirm
          window.location.href = "tel://13237126506";
        })
        .catch(() => {
          // on cancel
        });      
    },
    // 登录
    login() {
      console.log('系统关闭')
      let tip = "3月21日"
      Dialog.alert({
        title: "提示",
        message: `${tip}起系统暂时关闭，开放时间待通知......`
      });
      return
      if (!this.isChecked && this.active == 1) {
        Dialog.alert({
          title: "提示",
          message: "请勾选并阅读相关服务条款和隐私政策！"
        });
        return;
      }
      //效验
      let validationError = "";
      if (this.active == 0) {
        validationError = validation({
          isPassword: true,
          phone: this.phone,
          password: this.password
        });
      } else {
        validationError = validation({
          isPassword: false,
          phone: this.phone,
          verificationCode: this.code
        });
      }

      if (validationError === "") {
        //TODO:验证通过
        // 用户登录
        if (this.active == 0) {
          // 账号密码登录
          const params = {
            phone: this.phone,
            password: this.password
          };
          this.pwdLoginPost(params);
        } else {
          // 验证码登录
          const params = {
            phone: this.phone,
            code: this.code
          };
          this.codeLoginPost(params);
        }
      } else {
        Dialog.alert({
          title: "提示",
          message: validationError
        });
      }
    },
    pwdLoginPost(params) {
      console.log(config.get('bpp_url')+config.get('v'),'test')
      axios.get(config.get('bpp_url')+config.get('v')+'_login',{params})
        // pwdLogin(params)
        .then(res => {
          res = res.data
          if (res.code == 200) {
            console.log(res,'res')
            this.$store.commit("setToken",res.data.token);
            config.setUserInfo(res.data);
            console.log("get(userInfo)", config.get("userInfo"));
            this.$store.commit("setUser", res.data.user);
            sessionStorage.setItem("token",res.data.token);
            if(res.data.user.role_id == 2){
                // 判断是否有OA账号 首页给提示
                sessionStorage.setItem(
                "isOATipOver",
                res.data.expand_info[0].oa_phone && res.data.expand_info[0].oa_pwd
                    ? true
                    : false
            );
            }
            //判断是否实名认证
            sessionStorage.setItem(
              "isSmrzOver",
              res.data.errands_info &&
                res.data.errands_info[0].id_card_number
                ? true
                : false
            );
            //记住密码
            let $accountPassword = {
              phone: window.btoa(params.phone),
              password: window.btoa(params.password),
              isRememberPwd: this.isRememberPwd
            };
            localStorage.setItem(
              "$accountPassword",
              JSON.stringify($accountPassword)
            );
            Toast.success("欢迎您！");
            console.log(res.data.user.role_id,'id')
            if (res.data.user.role_id == 3) {
              var url = config.get("bpp_url");
              axios.get(url + "sys_init").then(res => {
                window.localStorage.setItem(
                  config.get("v") + "_init",
                  JSON.stringify(res.data.data.apireg)
                );
                this.$router.replace("/replace");
              });
            } else {
              var url = config.get("app_url");
              axios.get(url + "sys_init").then(res => {
                window.localStorage.setItem(
                  config.get("v") + "_init",
                  JSON.stringify(res.data.data.apireg)
                );
                this.$router.replace("/user/home");
              });
            }
          }
        })
        .catch(error => {
          this.password = "";
        });
    },
    codeLoginPost(params) {
      axios.get(config.get('bpp_url')+config.get('v')+'userCodeLogin',{params})
      .then(res => {
        res = res.data
        if (res.code == 200) {
          this.$store.commit("setToken", res.data.token);
          config.setUserInfo(res.data);
          this.$store.commit("setUser", res.data.user);
          sessionStorage.setItem("token", res.data.token);
          Toast.success("欢迎您！");
          if(res.data.user.role_id == 2){
                // 判断是否有OA账号 首页给提示
                sessionStorage.setItem(
                "isOATipOver",
                res.data.expand_info[0].oa_phone && res.data.expand_info[0].oa_pwd
                    ? true
                    : false
            );
          }
          //判断是否实名认证
          sessionStorage.setItem(
              "isSmrzOver",
              res.data.errands_info &&
                res.data.errands_info[0].id_card_number
                ? true
                : false
            );
          if (res.data.user.role_id == 3) {
            var url = config.get("bpp_url");
            axios.get(url + "sys_init").then(res => {
              window.localStorage.setItem(
                config.get("v") + "_init",
                JSON.stringify(res.data.data.apireg)
              );
              this.$router.replace("/replace");
            });
          } else {
            var url = config.get("app_url");
            axios.get(url + "sys_init").then(res => {
              window.localStorage.setItem(
                config.get("v") + "_init",
                JSON.stringify(res.data.data.apireg)
              );
              this.$router.replace("/user/home");
            });
          }
        } else {
          Dialog.alert({
            title: "提示",
            message: res.data
          });
        }
      });
    },

    // 获取验证码
    getVCode() {
      if (!this.isChecked) {
        Dialog.alert({
          title: "提示",
          message: "请勾选并阅读相关服务条款和隐私政策！"
        });
        return;
      }
      let that = this;
      if (/^1[3456789]\d{9}$/.test(that.phone)) {
        let params = {};
        params = {
          tel: that.phone,
          type: 2
        };
        axios.get(config.get('bpp_url')+config.get('v')+'getCodeLogin',{params})
        // getCode(params)
        .then(res => {
          res = res.data
          if (res.code === 200) {
            Toast.success("验证码发送成功！请注意查收。");
            let num = 60;
            that.btnIsDisabled = true;
            const timer = setInterval(function() {
              that.VCodeText = num + "秒后可重新发送";
              num -= 1;
              if (num < 0) {
                that.VCodeText = "发送验证码";
                that.btnIsDisabled = false;
                clearInterval(timer);
              }
            }, 1000);
          } else {
            Toast.fail("验证码发送失败！");
            that.btnIsDisabled = false;
            clearInterval(timer);
          }
        });
        this.isBool = false
      } else {
        Dialog.alert({
          title: "提示",
          message: "手机号不能为空且格式不能有误"
        });
      }
    },
    // 注册
    onRegister() {
      this.$router.push("register");
    }
  },
  watch: {
    code: function(value) {
      if (/^[\d]{6}$/.test(value)) {
        this.login();
      }
    }
  }
};
</script>

<style lang="less" scoped>
.van-field__label {
  display: flex;
  align-items: center;
  font-size: 14px;
  width: 20px;
}

.van-tab__text--ellipsis {
  font-size: 20px;
}

.van-password-input {
  margin: 0;
  margin-bottom: 10px;

  .password-input {
    // height: .96rem;
    // line-height: .96rem;

    &::after {
      border: none;
    }

    li {
      border-bottom: 1px solid #ebedf0;

      margin-right: 11px;
      box-sizing: border-box;
      // line-height: .96rem;

      &:last-child {
        margin-right: 0;
      }

      &::after {
        border: none;
      }
    }
  }
}

.van-cell {
  align-items: center;
  height: 60px;
  border-bottom: 0.026667rem solid #ebedf0;
}

.van-password-input {
  height: 50px;
}

.user-login {
  width: 100%;
  height: 100%;
  padding: 0.8rem 0.666667rem;
  box-sizing: border-box;
  color: #353535;

  .header-title {
    width: 100%;
    position: fixed;
    left: 0;
    top: 0;
    height: 1.333333rem;
    line-height: 1.333333rem;
    font-size: 0.533333rem;
    text-align: center;
    font-weight: 700;

    > div {
      height: 0.266667rem;
      background-color: #f5f5f5;
    }
  }

  .select-box {
    height: 100%;
  }

  .selct-user-type {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100%;
    text-align: center;

    .title {
      font-weight: 700;
      font-size: 0.533333rem;
      margin-bottom: 1.866667rem;
    }

    .icon-box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #000;

      &:nth-child(1) {
        margin-bottom: 1.333333rem;
      }

      &:nth-child(2) {
        margin-top: 1.333333rem;
      }

      img {
        margin-bottom: 0.253333rem;

        &:first-child {
          width: 3.586667rem;
          height: 3.266667rem;
        }

        &:last-child {
          width: 3.266667rem;
          height: 3.804933rem;
        }
      }

      > div {
        width: 3.2rem;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.426667rem;

        &:last-child {
          // margin-bottom: 1.6rem;
        }

        > span {
          display: inline-block;
          width: 0.426667rem;
          height: 0.426667rem;
          border-radius: 50%;
          border: 0.026667rem solid #006cff;
          margin-right: 0.266667rem;
        }

        > span.active {
          position: relative;

          &::after {
            position: absolute;
            left: 0.08rem;
            top: 0.08rem;
            content: "";
            width: 0.266667rem;
            height: 0.266667rem;
            border-radius: 50%;
            background-color: #006cff;
          }
        }
      }
    }
  }

  .login-box {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .get-code-btn {
      color: #006cff;
      font-size: 0.373333rem;
      height: 0.96rem;
      line-height: 0.96rem;
      border: none;
      background-color: #fff;
      padding: 0;
    }

    .check-box {
      border: 0.026667rem solid #006cff;
    }

    .agreement {
      display: flex;
      align-items: center;
      line-height: 17px;
      font-size: 12.5px;
      height: 65px;
      box-sizing: border-box;
    }
    .recBottom {
      margin-top: 15px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      div {
        color: #006cff;
        font-size: 14px;
      }
    }
    .logo {
      margin: 15px auto;
      width: 140px;
      height: 90px;
      > img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .button,
  .login-button {
    width: 100%;
    height: 1.2rem;
    line-height: 1.2rem;
    font-size: 0.426667rem;
  }

  .button {
    margin-top: 0.4rem;
  }

  center {
    position: fixed;
    /* bottom: 0; */
    left: 0;
    padding: 0.266667rem 0 0.8rem 0;
    box-sizing: border-box;
    font-size: 0.32rem;
  }
  .main-header {
    left: 0;
  }
}
.policy {
  text-align: center;
  font-size: 12.5px;
  color: rgba(0, 0, 0, 0.3);
  margin-bottom: 3%;
  z-index: 999;
  .policy_a {
    color: #4a90e2;
    font-size: 12.5px;
  }
}
</style>
